########################################################################
# prefs.py - Manages wickddup's user preference persistence mechansim.
#
# Created 2006.07.27 by Warren Young
#
# Copyright (c) 2006 by Pixel Corps.  This program may be used under
# the terms of the X11 license, a copy of which should have accompanied
# this program, in the LICENSE file.
########################################################################

import xml.dom.minidom

import os


class Preferences:
	"""
	Class to manage the app-wide preferences, to be remembered from one
	run of the program to the next.
	"""

	# Class constants
	fileName = 'wickddup.pref'

	def __init__(self):
		"""
		Initialize the default preferences, then call L{Load}.
		"""
	
		self.artisanName = None
		self.elementName = None
		self.hostName = None
		self.fileNameCheckLiterals = [None] * 8
		self.projectName = None
		self.sceneName = None
		self.remoteDirectory = None
		self.remoteDirectoryVariable = None
		self.userName = None
		
		self.dir = self.FindDir()
		if self.dir:
			self.fullPath = '%s%s%s' % (self.dir, os.path.sep,
					self.fileName)
			self.Load()
		else:
			self.fullPath = None

	
	def FindDir(self):
		"""
		Figure out the best place to store preference files, creating it
		if need be.
		"""

		if 'USERPROFILE' in os.environ:
			# Windows NT and derivatives
			dir = '%s%s%s%s%s' % (os.environ['USERPROFILE'], os.path.sep,
					'Application Data', os.path.sep, 'WickDD')
		elif 'HOME' in os.environ:
			# Unixy platforms, mainly
			dir = '%s%s%s' % (os.environ['HOME'], os.path.sep, '.wickdd')
		else:
			print 'PREFS: Failed to decide on prefs dir!'
			return None

		try:
			if not os.path.exists(dir):
				os.makedirs(dir, 0700)
			return dir
		except Exception, err:
			print 'PREFS: Failed to create prefs dir %s: %s' % (dir, err)

		return None


	def Load(self):
		"""
		Parses preference file stored on disk, saving data within to
		our pref member variables.
		"""

		try:
			doc = xml.dom.minidom.parse(self.fullPath)
			for p in doc.childNodes[0].childNodes:
				if p.nodeType == p.ELEMENT_NODE:
					val = p.childNodes[0].nodeValue
					if p.localName == 'artisan':
						self.artisanName = val
					elif p.localName == 'fncheck':
						self.fileNameCheckLiterals[
								int(p.getAttribute('index'))] = val
					elif p.localName == 'element':
						self.elementName = val
					elif p.localName == 'host':
						self.hostName = val
					elif p.localName == 'project':
						self.projectName = val
					elif p.localName == 'remotedir':
						self.remoteDirectory = val
					elif p.localName == 'remotedirvar':
						self.remoteDirectoryVariable = val
					elif p.localName == 'scene':
						self.sceneName = val
					elif p.localName == 'user':
						self.userName = val
					else:
						print 'PREFS: Ignoring unknown node %s!' % (
								p.localName)
		except Exception, err:
			print 'PREFS: Failed to read prefs file %s: %s' % (
					self.fullPath, err)


	def Save(self):
		"""Saves pref member variable values to file on disk."""

		if not self.fullPath:
			print 'PREFS: Path to preferences file not known; ignoring save.'
			return

		doc = xml.dom.minidom.Document()
		top = doc.createElement('prefs')
		doc.appendChild(top)

		prefs = {
			'artisan': self.artisanName,
			'element': self.elementName,
			'host': self.hostName,
			'fncheck': self.fileNameCheckLiterals,
			'project': self.projectName,
			'remotedir': self.remoteDirectory,
			'remotedirvar': self.remoteDirectoryVariable,
			'scene': self.sceneName,
			'user': self.userName,
		}
		keys = prefs.keys()
		keys.sort()
		for p in keys:
			if isinstance(prefs[p], list):
				# It's a list of values, so add a tag for each one
				for i in range(len(prefs[p])):
					if prefs[p][i]:
						ptag = doc.createElement(p)
						ptag.setAttribute('index', str(i))
						value = doc.createTextNode(prefs[p][i])
						ptag.appendChild(value)
						top.appendChild(ptag)
					else:
						print "PREFS: skipping blank list element", i
			elif prefs[p]:
				# It's a simple value and it isn't empty, so create a
				# tag for it.
				ptag = doc.createElement(p)
				value = doc.createTextNode(prefs[p])
				ptag.appendChild(value)
				top.appendChild(ptag)

		try:
			file = open(self.fullPath, 'w')
			file.write(doc.toxml('UTF-8'))
			file.close()
			print 'PREFS: Wrote %s successfully.' % self.fullPath
			#print 'PREFS: Pretty XML:'
			#print doc.toprettyxml(encoding = 'UTF-8')
		except Exception, err:
			print 'PREFS: failed to write pref file %s: %s' % (
					self.fullPath, err)

